module.exports = app => {
    const express = require('express')
    const assert = require('http-assert')
    const wxconfig = require ('../../config')
    const qs = require('querystring')
    const http = require('https')
    const jwt = require('jsonwebtoken')
    const customer = require('../../models/customer')
    const router = express.Router({
        mergeParams: true
    })

    const createToken = (rawData,openid)=>{
        let token = jwt.sign({
            "nickname": rawData.nickname,
            "gender": rawData.gender,
            "language": rawData.language,
            "city": rawData.city,
            "province": rawData.province,
            "country": rawData.country
        },openid)
        return token
      }
    
    app.post('/api/sign',async(req,res)=>{
        const { account_id, password, code, msg ,status,default_address } = req.body
        var userInfo = JSON.parse(msg)
        console.log(password)
        const user = await customer.findOne({account_id})
        if(user){
            console.log(user)
            return res.status(401).send('用户已存在')
        }
        var data = {
            appid: wxconfig.appid,
            secret: wxconfig.secret,
            js_code: code,
            grant_type: 'authorization_code'
        }
        var content = qs.stringify(data)
    var options = {  
        hostname: 'api.weixin.qq.com',  
        port: '',  
        path: '/sns/jscode2session?' + content,  
        method: 'GET' ,
        header: {
            "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        }, 
    };
    var _req = http.request(options, (_res)=>{  

        _res.on('data', async (_data)=> {  
            let newdata = JSON.parse(_data.toString())
            const openid = newdata.openid;
            const token = await createToken(userInfo,openid)
            const wx_name = userInfo.nickName
            var sercetData = {
                account_id: account_id,
                password: password,
                wx_name: wx_name,
                openid: openid,
                token: token,
               status:status,
               default_address:default_address
            }
            console.log(sercetData)
            const model = await customer.create(sercetData)
            res.send(model)
                          
        });  
        
    });  
      
    _req.on('error', (e)=> {  
        console.log('problem with request: ' + e.message);  
    });  

    _req.end();
})
    
    app.post('/api/login', async(req,res,next)=>{
        
        const { account_id, password,} = req.body
        // const user = await customer.findOne({ account_id }).select('+password')
        // console.log(user)
        // assert(user, 422, '用户不存在')
        // // 2.校验密码
        // const isValid = require('bcrypt').compareSync(password, user.password)
        // assert(isValid, 422, '密码错误')
        // // 3.返回token
        // const token = user.token
        // res.send({ token })
        // 1.根据用户名找用户
        const user = await customer.findOne({ account_id }).select('+password')
        if(user){
            // 2.校验密码
            const isValid = require('bcryptjs').compareSync(password, user.password)
            if(isValid){
                // 3.返回token
                if(user.status == "3"){
                    res.send({
                        shenfen:user.status,
                        iphone:user.account_id,
                        token:user.token,
                        shopping_cart:user.shopping_cart,
                        openid: user.openid,
                        local: user.default_address[0].service
                    })
                }else if(user.status == "2"){
                    res.send({
                        shenfen:user.status,
                        iphone:user.account_id,
                        token:user.token,
                        shopping_cart:user.shopping_cart,
                        openid: user.openid
                    })
                }else{
                    res.send({
                        shenfen:user.status,
                        iphone:user.account_id,
                        token:user.token,
                        shopping_cart:user.shopping_cart,
                        openid: user.openid,
                        service:user.address[0]
                    }) 
                }
            }else{
                res.send({status: 422,msg: '密码错误'})
            }
        }else{
            res.send({status: 422,msg: '用户不存在'})
        }
    });

    app.post('/api/changePass',async(req,res,next)=>{
        let {oldPass,newPass,account_id} = req.body
        const user = await customer.findOne({ account_id }).select('+password')
        const isValid = require('bcryptjs').compareSync(oldPass, user.password)
        if(isValid){
            await customer.updateOne({ account_id:account_id },{password:newPass})
            res.send({status:200})
        }else{
            res.send({status: 422,msg: '原密码错误'})
        }
    })
}